<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Api\Controllers\Auths;

use App\Api\BaseApi;
use App\Models\AdvanceCard;
use App\Models\AdvanceCardTransaction;
use App\Service\AdvanceCard\AdvanceCardService;

class AdvanceCardApi extends BaseApi
{
    public function getAdvanceCardSetting() //获取垫付卡配置
    {
        $res = AdvanceCardService::make()->getSetting();
        return responses($res);
    }

    public function getMyAdvanceCard()//获取我的垫付卡
    {
        $request = self::validate([
            'type' => 'required|in:0,1,2,3,4',
        ]);
        $type = $request->get('type');
        if ($type == 0) {
            $type = 2;
        }
        $res = AdvanceCard::query()
            ->where('user_id', self::UserId())
            ->when($type, function ($query, $value) {
                $query->where('status', $value);
            })->latest()->get();
        return responses($res);
    }

    public function getMyAdvanceCardTransactions()//获取我的垫付卡详情
    {
        $type = self::$request->get('type', 2);
        $res = AdvanceCardTransaction::query()
            ->when($type, function ($query, $value) {
                $query->where('type', $value);
            })
            ->where('user_id', self::UserId())
            ->latest()
            ->simplePaginate(request('perPage', 10));

        return responses($res);
    }

    public function rechargeAdvancePayment() //充值垫付金
    {
        $request = self::validate([
            'id' => 'required|numeric',
            'amount' => 'required',
        ]);
        $advanceCard = AdvanceCard::query()
            ->where('user_id', self::UserId())
            ->find($request->get('id'));
        if ($advanceCard->status != 2) {
            //代金券
            return responses('无效的垫付卡,请检查该垫付卡是否正常使用状态', 7);
        }
        $res = AdvanceCardService::make()->recharge($advanceCard, $request->get('amount'));
        if ($res['flag']) {
            return responses($res['msg']);
        }
        return responses($res['msg'], 7);
    }
}
